<template>
  <div class="collection">
    <NavBar title="我的收藏" />
    <van-cell title="">
      <div @click="flg = !flg">{{ flg ? '取消' : '管理' }}</div>
    </van-cell>
    <!-- 商品 -->
    <van-grid :column-num="2" :gutter="20">
      <van-grid-item v-for="(item, index) in list" :key="index">
        <template slot="icon">
          <van-checkbox v-model="item.state" v-if="flg" />
          <img :src="(API.BASE_SERVER_URL + item.product.defaultImg) || '#'" alt="">
        </template>
        <template slot="text">
          <div class="texttracks">{{ item.product.name | isname }}</div>
          <div class="tracksPrice">￥{{ (item.product.shopPrice / 100).toFixed(2) }}</div>
        </template>
      </van-grid-item>
    </van-grid>
    <!-- 删除按钮 -->
    <van-submit-bar button-text="删除" @submit="onSubmit" v-if="flg">
      <van-checkbox v-model="checked">全选</van-checkbox>
      <div class="checkedbox"></div>
    </van-submit-bar>
  </div>
</template>
<script>
export default {
  data () {
    return {
      flg: false,
      list: [{ state: false, product: { defaultImg: '' } }]
    }
  },
  methods: {
    async loadData () {
      const { data: res } = await this.$post(this.API.API_URL_CUSTOMER_WISHLIST + '/1', {
        userId: localStorage.getItem('userId')
      })
      if (res) {
        res.wishlist.forEach(item => {
          item.state = false
        })
        this.list = res.wishlist
      }
    },
    async onSubmit () {
      if (!this.flg) return false
      const arr = this.list.filter(item => item.state) // 获取被选中的数据列表
      if (arr.length) {
        await arr.forEach(item => {
          this.remove(item.id)
        })
        this.$toast.success('删除成功!')
      }
    },
    async remove (id) {
      const { data: res } = await this.$post(this.API.API_URL_CUSTOMER_REMOVE_WISHLIST, {
        userId: localStorage.getItem('userId'),
        id: id
      })
      if (res) {
        this.list.some((item, i) => {
          if (item.id === id) {
            this.list.splice(i, 1)
            return true
          }
        })
      }
    }
  },
  created () {
    this.loadData()
  },
  computed: {
    checked: {
      get () {
        if (!this.flg) return false
        return this.list.every(item => item.state)
      },
      set () {
        if (!this.flg) return false
        if (this.checked) {
          this.list.forEach(item => { item.state = false })
        } else this.list.forEach(item => { item.state = true })
      }
    }
  },
  filters: {
    isname (val) {
      if (!val) return ''
      return val.length >= 20 ? val.slice(0, 20) : val
    }
  }
}
</script>
<style scoped>
.van-grid {
  position: relative;
}
.van-grid-item__icon-wrapper img {
  width: calc(100% - 60px);
}
.van-grid-item__icon-wrapper .van-checkbox {
  position: absolute;
  top: -17px;
  left: -2px;
}
.texttracks, .tracksPrice {
  margin: 8px 5px;
  text-align: left;
  width: 100%;
}
.tracksPrice {
  color: #f19f24;
}
.checkedbox {
  width: 160px;
}
</style>
